package com.hua.yuan.live;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.hua.yuan.base.BaseAppActivity;
import com.hua.yuan.base.Constents;
import com.hua.yuan.live.adapter.DisplayLiveAdapter;
import com.hua.yuan.live.fragment.LiveFragment;
import com.hua.yuan.live.listener.OnLiveClickListener;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveSearchIndexLoader;
import com.hua.yuan.live.repertory.cloud_data.res.RoomBean;
import com.jet.flowtaglayout.FlowTagLayout;
import java.util.List;
import cm.hua.yuan.common.utils.PreferenceUtils;

/**
 * 时间：2018/8/20
 * 作者：蓝天
 * 描述：主播搜索
 */
public class LiveSearchActivity extends BaseAppActivity implements View.OnClickListener,
        LoaderManager.LoaderCallbacks<List<RoomBean>>,
        FlowTagLayout.OnTagClickListener,OnLiveClickListener {

    private FlowTagLayout flowTagLayout_history;
    private TextView tv_cancel;
    private EditText et_search_live;
    private ImageView iv_search_icon;
    private ListView lv_list_livesearch;
    public final static int TASK_ID = 1000;

    private DisplayLiveAdapter mAdapter;

    private final static String TAG = LiveFragment.class.getSimpleName();

    private final int resutltCode = 1001;

    private final int searchResultCode = 1002;

    private TextView tv_history_search_hint;

    private final String SEARCH_KEY_CODE = "LIVE_SEARCH_KEY";

    private LiveSearchIndexLoader mLoader;


    @Override
    protected int initLayoutId() {
        mLoader = (LiveSearchIndexLoader) getSupportLoaderManager().initLoader(TASK_ID, null, this);
        return R.layout.activity_live_search;
    }

    @Override
    protected void initView() {
        flowTagLayout_history = findViewById(R.id.flowTagLayout_history);
        tv_cancel = findViewById(R.id.tv_cancel);
        et_search_live = findViewById(R.id.et_search_live);
        iv_search_icon = findViewById(R.id.iv_search_icon);
        lv_list_livesearch = findView(R.id.lv_list_livesearch);
        this.mAdapter = new DisplayLiveAdapter(this, this);
        lv_list_livesearch.setAdapter(mAdapter);
        tv_history_search_hint = findView(R.id.tv_history_search_hint);
        iv_search_icon.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        et_search_live.addTextChangedListener(mTextWatcher);
        flowTagLayout_history.setTagClickListener(this);
        lv_list_livesearch.setVisibility(View.GONE);
    }

    private TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (TextUtils.isEmpty(s)) {
                initNet();
                tv_history_search_hint.setVisibility(View.VISIBLE);
                flowTagLayout_history.setVisibility(View.VISIBLE);
                lv_list_livesearch.setVisibility(View.GONE);
            }
        }
    };

    @Override
    protected void initNet() {
        if (LiveModule.searchList.size() == 0) {
            String jsonKey = PreferenceUtils.getString(SEARCH_KEY_CODE, "");
            if (!TextUtils.isEmpty(jsonKey)) {
                LiveModule.searchList = JSON.parseArray(jsonKey, String.class);
            }
        }
        // 添加tag
        // 添加tag的列表，该方法会把之前的tags全部清空
        flowTagLayout_history.addTags(LiveModule.searchList);
    }

    @Override
    public void onClick(View v) {

        if (R.id.iv_search_icon == v.getId()) {

            if (!TextUtils.isEmpty(et_search_live.getText())) {
                String keyworld = et_search_live.getText().toString();
                mLoader.requestData("", keyworld);
                mLoader.forceLoad();
                if (!LiveModule.searchList.contains(keyworld)) {
                    LiveModule.searchList.add(keyworld);
                }
            }
        }

        if (R.id.tv_cancel == v.getId()) {

            onBackPressed();
        }
    }


    private boolean checkLogin() {
        String token = PreferenceUtils.getString(Constents.TOKEN);
        return TextUtils.isEmpty(token);
    }

    @NonNull
    @Override
    public Loader<List<RoomBean>> onCreateLoader(int id, @Nullable Bundle args) {

        return new LiveSearchIndexLoader(this);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<RoomBean>> loader, List<RoomBean> data) {
        if (data == null) {
            return;
        }
        mAdapter.setData(data);
        if (TextUtils.isEmpty(et_search_live.getText())) {
            return;
        }
        lv_list_livesearch.setVisibility(View.VISIBLE);
        tv_history_search_hint.setVisibility(View.GONE);
        flowTagLayout_history.setVisibility(View.GONE);
    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<RoomBean>> loader) {

    }

    @Override
    public void gotoLiveRoom(int position) {

        boolean isLogin = checkLogin();
        if (isLogin) {
            Intent intent = new Intent();
            intent.setClassName(this, "com.hua.yuan.ui.LoginActivity");
            if (this.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                startActivity(intent);
            }
            return;
        }
        RoomBean roomBean = (RoomBean) mAdapter.getData().get(position);
        if (roomBean == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, LiveRoomActivity.class);
        //直播的房间号
        intent.putExtra(LiveModule.INTENT_ANCHOR_ID, roomBean.getAnchorId());
        intent.putExtra(LiveModule.INTENT_ANCHOR_NICK_NAME, roomBean.getNickName());
        intent.putExtra(LiveModule.INTENT_ANCHOR_ONLINE, roomBean.getViewNum());
        intent.putExtra(LiveModule.INTENT_ANCHOR_ROOM_NO, roomBean.getRoomNo());
        intent.putExtra(LiveModule.INTENT_ANCHOR_IS_LIVE, roomBean.getIsLive());
        intent.putExtra(LiveModule.INTENT_GROUP_ID, roomBean.getGroudId());
        intent.putExtra(LiveModule.INTENT_ANCHOR_RTC_USER_ID, roomBean.getRtcUserId());
        if (this.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {

            startActivityForResult(intent, resutltCode);
        }
    }

    @Override
    public void gotoLiveDetail(int position) {
        boolean isLogin = checkLogin();
        if (isLogin) {
            Intent intent = new Intent();
            intent.setClassName(this, "com.hua.yuan.ui.LoginActivity");
            if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                startActivity(intent);
            }
            return;
        }
        RoomBean roomBean = (RoomBean) mAdapter.getData().get(position);
        if (roomBean == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(this, AnchorDetailActivity.class);
        //直播的房间号
        intent.putExtra(LiveModule.INTENT_ANCHOR_ID, roomBean.getAnchorId());
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivityForResult(intent, resutltCode);
        }
    }

    @Override
    public void onBackPressed() {
        if (LiveModule.searchList.size() > 0) {
            PreferenceUtils.setPreferences(SEARCH_KEY_CODE, JSON.toJSONString(LiveModule.searchList));
        } else {
            PreferenceUtils.setPreferences(SEARCH_KEY_CODE, "");
        }
        setResult(searchResultCode);
        finish();
    }

    @Override
    public void tagClick(int position) {
        if(position>LiveModule.searchList.size()){
            return;
        }
        flowTagLayout_history.getChildAt(position).setSelected(!flowTagLayout_history.getChildAt(position).isSelected());
        et_search_live.setText(LiveModule.searchList.get(position));
        mLoader.requestData("",et_search_live.getText().toString());
        mLoader.forceLoad();
    }
}
